<?php

// +----------------------------------------------------------------------
// |ZBPHP[基于ThinkPHP5.1开发]
// +----------------------------------------------------------------------
// | Copyright (c) 2016-2019 http://www.benbenwangluo.com
// +----------------------------------------------------------------------
// | Author 似水星辰 [ 2630481389@qq.com ]
// +----------------------------------------------------------------------
// | 中犇软件 技术六部 出品
// +----------------------------------------------------------------------
namespace app\order\admin;

use app\admin\admin\Base;
use think\Db;
use service\Format;
use app\order\model\OrderGoodsExpress;
use app\common\model\Order as OrderModel;
use app\order\model\OrderInvoice;
use app\order\model\OrderAction;
use app\order\model\OrderGoods;
use app\order\model\OrderInfo;

/**
 * 订单物流
 * @author 晓风<215628355@qq.com>
 * @date 2021-11-6 17:16:08
 */
class Express extends Base {

    
    /**
     * 订单物流
     * @return mixed
     */
    public function express()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        $order_sn = input('param.order_sn');
        $express_no = input('param.express_no');
        $shipping_type = input('param.shipping_type');
        $shipping_time = input('param.shipping_time');
        $receiver_name = input('param.receiver_name');
        $receiver_mobile = input('param.receiver_mobile');

        // 查询
        $map = [];
        if ($order_sn) {
            $map[] = ['oge.order_sn', '=', $order_sn];
        }
        if ($express_no) {
            $map[] = ['oge.express_no', '=', $express_no];
        }
        if ($shipping_time) {
            $map[] = ['oge.shipping_time', '>=', strtotime($shipping_time)];
            $map[] = ['oge.shipping_time', '<', (strtotime($shipping_time . ' 23:59:59'))];
        }
        if ($shipping_type !== '' && !is_null($shipping_type)) {
            $map[] = ['oge.shipping_type', '=', $shipping_type];
        }
        if ($receiver_name) {
            $map[] = ['ogi.receiver_name', 'like', '%' . $receiver_name . '%'];
        }
        if ($receiver_mobile) {
            $map[] = ['ogi.receiver_mobile', 'like', '%' . $receiver_mobile . '%'];
        }

        // 排序
        $order = 'id desc';
        // 数据列表
        $data_list = \think\Db::name('order_goods_express')
            ->alias('oge')
            ->leftJoin('order_goods_info ogi', 'ogi.order_sn = oge.order_sn')
            ->where($map)
            ->field('oge.*, ogi.receiver_mobile, ogi.receiver_address, ogi.receiver_name')
            ->order($order)
            ->paginate(10)
            ->each(function ($item) {
                if ($item['shipping_type'] == 1) {
                    $item['shipping_type'] = lang('需要物流');
                } else {
                    $item['shipping_type'] = lang('无需物流');
                }
                return $item;
            });
        $this->assign('list', $data_list);
        $this->assign('pages', $data_list->render());
        return $this->fetch();
    }
    
    /**
     * 订单物流添加
     * 直接发货
     * @author 晓风<215628355@qq.com>
     */
    public function express_add($order_sn)
    {       
         // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            
            Db::startTrans();
            try {
                $param = OrderGoodsExpress::addExpress($data);
                //更新发票
                $invoice = OrderInvoice::where(['order_sn' => $order_sn, 'billing_type' => 1])->find();
                if ($invoice) {            
                    $rs = OrderInvoice::where(['order_sn' => $order_sn, 'billing_type' => 1])->update([
                        'invoice_status' => 2,
                        'invoice_send_goods_num' => $param['express_no'], 
                        'express_company_id' => $param['express_company_id']
                    ]);
                    if (!$rs) {
                        exception(lang('发货失败'));
                    }
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage(), cookie('__forward__'));
            }
            $this->success('添加成功', 'order/order/index?order_sn='.$order_sn);
        }
       
        $sender_list = Db::name('goods_express_sender')->column('id,name');
        $express_company = Db::name('goods_express_company')->column('aid,name');
        $fields = [
            ['type' => 'hidden', 'name' => 'order_sn', 'value' => $order_sn],    
            ['type' => 'select', 'name' => 'express_company', 'title' => lang('请选择快递公司'), 'tips' => '', 'extra' => $express_company],
            ['type' => 'select', 'name' => 'sender_id', 'title' => lang('请选择发件地址'), 'tips' => '', 'extra' => $sender_list],
            ['type' => 'text', 'name' => 'express_no', 'title' => lang('请输入物流单号'), 'tips' => '', 'attr' => ''],
            ['type' => 'text', 'name' => 'memo', 'title' => '备注','tips' => '', 'attr' => ''], 
    
        ];
        $this->assign('page_title', lang('添加物流'));
        $this->assign('form_items', $fields);
        $this->assign('set_script', ['/static/goods/js/express.js']);
        return $this->fetch('admin@public/add');
    }


    public function express_del($eid)
    {
        $rs = \think\Db::name('order_goods_express')->delete($eid);
        if ($rs) {
            action_log('order_express_delete', 'goods', 0, UID);
            $this->success(lang('删除成功'), cookie('__forward__'));
        } else {
            $this->error(lang('删除失败'), cookie('__forward__'));
        }
    }
    
    /**
     * 生成发货单--页面
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function create_express()
    {
        $order_sn = input("param.order_sn");
        $info = OrderInfo::get_order_detail($order_sn);
        $userId = $info['user_id'];
        $info['order_status'] = OrderModel::$order_status[$info['status']];
//        $info['pay_status'] = OrderModel::$pay_status[$info['pay_status']];
        $info['pay_status_name'] = OrderModel::$pay_status[$info['pay_status']];

//        $info['order_type'] = OrderModel::order_typeArr()[$info['order_type']]['name'];
        $info['order_type_name'] = OrderModel::order_typeArr()[$info['order_type']]['name'];

        $info['pay_type'] = OrderModel::$payTypes[$info['pay_type']];


        $info['order_express'] = Db::name('order_goods_express')->where(['order_sn' => $info['order_sn']])->find();
        if ($info['order_type'] != 1) {
            $map[] = ['order_sn', '=', $info['order_sn']];
        }
        $info['comment_time'] = Db::name('goods_comment')->where($map)->where([['user_id', '=', $info['user_id']]])->value('create_time');
        if ($info['order_type'] == 7) {
            $final_order_sn = Db::name('order_relation')->where(['book_order_sn' => $info['order_sn']])->value('final_order_sn');

            $final_order = Db::name('order')->where(['order_sn' => $final_order_sn])->find();
            $final_order['pay_status_name'] = OrderModel::$pay_status[$final_order['pay_status']];
            $final_order['transaction_no'] = Db::name('payment_log')->where(['order_sn' => $final_order['user_id']])->value("transaction_no");
            $final_order['pay_type'] = OrderModel::$payTypes[$final_order['pay_type']];

            $info['final_order'] = $final_order;
            if ($final_order['pay_status'] == 1) {
                $info['pay_status'] = 2;
                $info['pay_status_name'] = lang('已付款');
            } else {
                $info['pay_status_name'] = lang('未付款');
            }
        }
        $userInfo = getUserInfo($userId);
        $info['user'] = [
            'user_name' => $userInfo['user_name'],
            'mobile' => $userInfo['mobile'],
        ];
        $info['order_goods'] = json_encode($info['order_goods'], JSON_UNESCAPED_UNICODE);
        $express_company = Db::name('goods_express_company')->field('aid,name')->select();
        $sender_list = Db::name('goods_express_sender')->field('id,name')->select();
        $order_action = OrderAction::getActionLogs([["order_sn", "=", $order_sn]]);
        $this->assign('order_action', json_encode($order_action->toArray()['data'], JSON_UNESCAPED_UNICODE));
        $this->assign('sender_list', json_encode($sender_list, JSON_UNESCAPED_UNICODE));
        $this->assign('express_company', json_encode($express_company, JSON_UNESCAPED_UNICODE));
        $this->assign('sender_company', json_encode($sender_list, JSON_UNESCAPED_UNICODE));
        $this->assign('order_info', $info);
        return $this->fetch();
    }
     /**
     * 生成发货单--操作
     */
    public function create_express_operation()
    {
          // 商品列表
        $data = input("param.");
        $order_sn = input("param.order_sn");
        $remark = $data['remark'] ?? '';       
        Db::startTrans();
        try{
             OrderGoodsExpress::createExpress([
                "order_sn"=>$order_sn,
                "express_company"=>$data['express_company'],
                "sender_id"=>$data['sender_company'],
                "remark"=>$remark,
           ]);     
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }        
        $this->redirect("express_index" ,["order_sn"=>$order_sn]);
    }
    
     private function create_ecpress_data($order_sn,$express_company_id,$sender_company_id , $remark = ""){         
         
        return true;
    }
    
      /**
     * 批量生产发货单
     * @return mixed
     * @throws \think\exception\DbException
     */

    public function create_express_all(){
        $ids = $this->request->param("ids");
        if(!$ids){
            $this->error("缺少参数");
        }  
        if($this->request->post() ){
            $data = input("param.");    
            $remark = $data['remark'] ?? '';
            $orders = OrderModel::where("aid","in",$ids)->field("status,order_sn")->select();
            Db::startTrans();
            try{
                foreach($orders as $order){
                   if($order["status"] != 1){
                        throw new \Exception(lang('订单状态不正确') .":". $order["order_sn"] );
                   }                   
                   OrderGoodsExpress::createExpress([
                        "order_sn"=>$order["order_sn"],
                        "express_company"=>$data['express_company'],
                        "sender_id"=>$data['sender_company'],
                        "remark"=>$remark,
                   ]); 
                }
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage());
            } 
           $this->redirect("express_index" ,["order_sn"=>$order_sn]);
        }      
        $express_company = Db::name('goods_express_company')->field('aid,name')->select();
        $sender_list = Db::name('goods_express_sender')->field('id,name')->select();
        $this->assign('sender_list', json_encode($sender_list, JSON_UNESCAPED_UNICODE));
        $this->assign('express_company', json_encode($express_company, JSON_UNESCAPED_UNICODE));
        $this->assign('sender_company', json_encode($sender_list, JSON_UNESCAPED_UNICODE));
        return $this->fetch();
    }
    /**
     * 发货单列表
     * @return mixed
     * @throws \think\exception\DbException
     */
    public function express_index()
    {
        cookie('__forward__', $_SERVER['REQUEST_URI']);
        // 查询
//        $map = $this->getMap();
        $param = input("param.");
        $order_sn = $param['order_sn'];
        $map[] = ["oge.is_del", '=', 0];

        if ($order_sn) {
            $map[] = ["oge.order_sn", '=', $order_sn];
        }
        if ($param['express_serial_number']) {
            $map[] = ["oge.express_serial_number", '=', $param['express_serial_number']];
        }
        if ($param['user_nickname']) {
            $map[] = ['u.user_nickname', 'like', '%' . $param['user_nickname'] . '%'];
        }
        if ($param['mobile']) {
            $map[] = ['u.mobile', 'like', '%' . $param['mobile'] . '%'];
        }
        if ($param['receiver_name']) {
            $map[] = ['ogi.receiver_name', 'like', '%' . $param['receiver_name'] . '%'];
            // $order_sn_data = OrderInfo::where("receiver_name","like",'%'.$param['receiver_name'].'%')->column("order_sn");
        }
        if ($param['receiver_address']) {
            $map[] = ['ogi.receiver_address', 'like', '%' . $param['receiver_address'] . '%'];
        }
        if ($param['receiver_mobile']) {
            $map[] = ['ogi.receiver_mobile', 'like', '%' . $param['receiver_mobile'] . '%'];
        }

        if ($param['express_status'] != 'all' && $param['express_status'] !== '' && $param['express_status'] !== null) {
            $map[] = ["oge.express_status", '=', $param['express_status']];
        }
        $map[] = ["oge.is_del", '=', 0];
        // 数据列表
        $data_list = OrderGoodsExpress::alias('oge')
            ->join("order o", "oge.order_sn = o.order_sn", "left")
            ->join("user u", "o.user_id = u.id", "left")
            ->join("order_goods_info ogi", "o.order_sn = ogi.order_sn", "left")
            ->field("oge.express_no,oge.id,oge.uid,oge.express_serial_number,oge.order_sn,oge.shipping_time,oge.express_status,oge.admin_name,o.create_time,o.user_id,u.user_nickname,u.mobile,ogi.receiver_name,ogi.receiver_mobile,ogi.receiver_address,o.status")
            ->where($map)
            // ->where(function ($query) use ($order_sn_data) {
            //     foreach ($order_sn_data as $v) {
            //         $query->whereOr('oge.order_sn', 'eq', $v);
            //     }
            // })
            ->order('oge.id desc')
            ->paginate()
            ->each(
                function ($item) {
                    if (in_array($item['status'], [3, 4])) {
                        $item['express_status'] = 2;
                    }
                    $item['order_sn_link'] = "<a href='" . url('order/detail', ['order_sn' => $item['order_sn']]) . "'>" . $item['order_sn'] . "</a>";                  
                    $item['admin_name'] = Db::name("admin")->where("id", $item['uid'])->value('username');
                    return $item;
                }
            );
        $fields = [
            ['id', 'ID'],
            ['express_serial_number', lang('发货流水单号')],
            ['order_sn_link', lang('订单号')],
            ['express_no', lang('发货单号')],
            ['create_time', lang('下单时间')],
            ['user_nickname', lang('下单人')],
            ['mobile', lang('下单人手机号')],
            ['receiver_name', lang('收货人')],
            ['receiver_mobile', lang('收货人手机号')],
            ['receiver_address', lang('收货人地址')],
            ['shipping_time', lang('发货时间'), 'callback', function ($value, $format) {
                return format_time($value, $format); // $format 在这里的值是Y-m
            }, 'Y-m-d H:i:s'],
            ['express_status', lang('状态'), 'status', '', ['all' => lang('全部'), 0 => lang('未发货'), 1 => lang('已发货'), '2' => lang('已完成')]],
            ['admin_name', lang('操作人')],
            ['right_button', lang('操作'), 'btn', '', '']
        ];
        $searchFields = [
            ['order_sn', lang('订单号'), 'text'],
            ['express_serial_number', lang('发货流水单号'), 'text'],
            ['user_nickname', lang('下单人'), 'text'],
            ['mobile', lang('下单人手机号'), 'text'],
            ['receiver_name', lang('收货人'), 'text'],
            ['receiver_mobile', lang('收货人手机号'), 'text'],
            ['receiver_address', lang('收货人地址'), 'text'],
            ['express_status', lang('状态'), 'select', '', ['all' => lang('全部'), 0 => lang('未发货'), 1 => lang('已发货')]],
        ];
        return Format::ins()//实例化
        ->setTopButtons([
            //['ident' => 'express_delete', 'title' => lang('批量删除'), 'href' => 'express_delete', 'icon' => 'fa fa-times pr5', 'class' => 'btn btn-sm mr5 btn-default  ajax-post confirm', 'extra' => 'target-form="ids"'],
            ['ident' => 'deliver_goods', 'title' => lang('批量发货'), 'href' => 'deliver_goods', 'icon' => 'fa pr5 fa-check-square', 'class' => 'btn btn-sm mr5 btn-primary plfh', 'extra' => 'target-form="ids"']])
//            ['ident' => 'deliver_goods', 'title' => lang('批量发货'), 'href' => ['deliver_goods', ['layer' => 1, 'id' => '__id__']], 'data-toggle' => 'dialog-right', 'icon' => 'fa fa-plus pr5', 'class' => 'btn btn-xs mr5 btn-success btn-flat','extra' => 'target-form="ids"']])
            ->addColumns($fields)//设置字段
            ->setRightButtons([
                ['ident' => 'express_detail', 'title' => lang('查看'), 'href' => ['express_detail', ['id' => '__id__', 'order_sn' => '__order_sn__']], 'icon' => 'fa fa-pencil pr5', 'class' => 'btn btn-xs mr5 btn-default'],
                ['ident' => 'express_delete', 'title' => lang('删除'), 'href' => ['express_delete', ['ids' => '__id__']], 'icon' => 'fa fa-times pr5', 'class' => 'btn btn-xs mr5 btn-default  ajax-get confirm'],
            ])
            ->setTopSearch($searchFields)
             ->replaceRightButton(['express_status'=>['>',0]], '','express_delete')
            ->setData($data_list)//设置数据
            ->fetch();//显示
    }

   
    
    /**
     * 批量发货展示发货详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function deliver_goods()
    {
        $ids = input("param.ids");
        if (!$ids) {
            $this->error(lang('参数错误'));
        }
        $map[] = ["oge.is_del", '=', 0];
        $map[] = ["oge.id", "in", $ids];
        // 数据列表
        $data_list = OrderGoodsExpress::alias('oge')
            ->join("order_goods_info o", "oge.order_sn = o.order_sn", "left")
            ->field("oge.id,oge.express_serial_number,oge.order_sn,oge.shipping_time,
            oge.express_status,o.receiver_mobile,o.receiver_address,province,city,district,receiver_name,express_company")
            ->where($map)
            ->order('oge.id desc')
            ->select();
        $this->assign("data_list", json_encode($data_list, JSON_UNESCAPED_UNICODE));
        return $this->fetch();
    }

    public function express_delete($ids)
    {
        Db::startTrans();
        try {
            if (is_array($ids)) {
                foreach ($ids as $k => $v) {
                    Db::name("order_goods_express")->where(['id' => $v])->setField('is_del', 1);
                }
            } else {
                Db::name("order_goods_express")->where(['id' => $ids])->setField('is_del', 1);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error(lang('删除失败'));
        }
        $this->success(lang('删除成功'));
    }

    /**
     * 订单发货
     * @return false|string
     */
    public function express_create()
    {
        $data = input("param.");
        if (empty($data)) {
            return json_encode(["code" => 0, "data" => [], "msg" => lang('参数错误')]);
        }
        Db::startTrans();
        try {
            foreach ($data['data'] as  $v) {
                $info = OrderGoodsExpress::setExpress($v['id'], $v['express_no'],$data['remark']);     
                OrderInvoice::where(['order_sn' => $info["order_sn"], 'billing_type' => 1])->update([
                    'invoice_status' => 2, 
                    'invoice_send_goods_num' => $info['express_no'], 
                    'express_company_id' => $info['express_company_id']
                ]);                 
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return json_encode(["code" => 0, "data" => [], "msg" => $e->getMessage()]);
        }
        return json_encode(["code" => 1, "data" => [], "msg" => lang('发货成功')]);
    }

    /**
     * 发货单详情
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function express_detail()
    {
        $express_id = input("param.id");
        $order_sn = input("param.order_sn");
        $info = OrderInfo::get_order_detail($order_sn);
        $info['order_express'] = Db::name('order_goods_express')->where(['order_sn' => $order_sn])->find();        
      
        $info['order_goods'] = json_encode($info['order_goods'], JSON_UNESCAPED_UNICODE);
        $order_action = OrderAction::getActionLogs([["order_sn", "=", $order_sn]]);
        $this->assign('order_action', json_encode($order_action->toArray()['data'], JSON_UNESCAPED_UNICODE));

        // 查询发票信息 ADD zenghu 2020年12月8日14:07:28
        $orderInvoice = OrderInvoice::get(['order_sn' => $order_sn]);
        if (!empty($orderInvoice)) {
            $orderInvoice['invoice_type_name'] = ['1' => lang('个人发票'), '2' => lang('公司发票')][$orderInvoice['invoice_type']];
            $orderInvoice['invoice_status'] = ['1' => lang('申请开票中'), '2' => lang('已开票')][$orderInvoice['invoice_status']];
            $orderInvoice['invoice_add_time'] =
                $orderInvoice['invoice_add_time']
                    ? date("Y-m-d H:i:s", $orderInvoice['invoice_add_time']) : '';
        }

        //购物人
        $buy = Db::name("user")->where(['id' => $info['user_id']])->value("user_nickname");
        $this->assign('buy', $buy);
        $this->assign('orderInvoice', $orderInvoice);
        $this->assign('order_info', $info);
        $this->assign('order_sn', $order_sn);
        $this->assign('express_id', $express_id);
        return $this->fetch();
    }

    /**
     * 单条发货单发货
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function edit_express()
    {
        $param = input("param.");
        $remark = $param['remark'] ?? '';
        if (!$param) {
            $this->error(lang('参数错误'));
        }       
        if ($param['type'] == "confirm") {            
               Db::startTrans();
               try {          
                    $info = OrderGoodsExpress::setExpress($param['express_id'],  $param['express_no'] , $remark);  
                    OrderInvoice::where(['order_sn' => $info["order_sn"], 'billing_type' => 1])->update([
                        'invoice_status' => 2, 
                        'invoice_send_goods_num' => $info['express_no'], 
                        'express_company_id' => $info['express_company_id']
                    ]);                  
                   Db::commit();
               } catch (\Exception $e) {
                   Db::rollback();
                   $this->success(lang('发货失败'.$e->getMessage()));                 
               }
               $this->success(lang('发货成功'));
        }
        if ($param['type'] == "cancel") {            
              Db::startTrans();
               try {          
                    $info = OrderGoodsExpress::canalExpress($param['express_id'],$remark);   
                    OrderInvoice::where(['order_sn' => $info['order_sn']])->update(['invoice_send_goods_num' => '', 'invoice_status' => 1]);          
                    OrderModel::where("order_sn", $info['order_sn'])->update(['invoice_status' => 1]);                
                   Db::commit();
               } catch (\Exception $e) {
                   Db::rollback();
                   $this->success(lang('取消失败'.$e->getMessage()));                 
               }
              $this->success(lang('取消成功'));
        }
        $this->success(lang('操作失败'));
    }

     //获取快递公司名称
    public function get_express_company()
    {
        $express_company = Db::name('goods_express_company')->field('aid,name')->select();
        if (count($express_company) > 0) {
            echo json_encode(array('ret' => 1, 'data' => $express_company));
        } else {
            echo json_encode(array('ret' => 0, 'data' => ''));
        }
    }
    
    /**
     * 确认订单商品已到达自提点
     * @param string order_sn 订单号
     * @return {*}
     * @Author: wangph
     * @Date: 2021-04-19 18:01:59
     */
    public function pickup_arrive()
    {
        $order_sn = input("param.order_sn");
        //订单状态变为已发货
        $r = OrderModel::where("order_sn", $order_sn)->setField("status", 2);
        if (!$r) {
            $this->error(lang('处理失败'));
        }
        //给用户发送消息通知-可以自提了
        $user_id = OrderModel::where(['order_sn' => $order_sn])->value("user_id");
        //自提点信息
        $pickup_info = \app\order\model\OrderPickup::getOrderPickUp($order_sn);
    
        $thumb = OrderGoods::where("order_sn",$order_sn)->value("goods_thumb");
       \app\operation\model\SystemMessage::create([
            "to_user_id"=> $user_id, 
            "title"=>'您的订单已到自提点',
            "order_sn"=>$order_sn,
            "content"=> "您的订单：" . $order_sn . ", 已到自提点，\n快递公司：". $pickup_info['deliver_name'] . "，请及时前往取货：",        
            "msg_type"=>2,    
            "thumb"=>$thumb ?:0,
            "custom"=>json_encode(['type'=>'order','id'=>  $order_sn])
        ]);                
        $this->success("OK");
        return;
    }

    
       /**
     * 根据用户id获取收货地址
     */
    public function ajaxClass_address()
    {
        $user_id = input('param.user_id');
        if (isset($user_id) && $user_id != 0) {
            $data_list = Db::name('user_address')->where(['user_id' => $user_id, 'status' => 1])->order('is_default DESC')->select();
            $user_level = Db::name('user')->where(['id' => $user_id, 'status' => 1])->value('user_level');
        }
        return json(array('ret' => 2, 'data' => $data_list, 'user_level' => $user_level, 'msg' => lang('查询成功')));
    }


    /**
     * 根据用户id获取收货地址
     */
    public function ajaxClass_pickup()
    {
        $user_id = input('param.user_id');
        if (isset($user_id) && $user_id != 0) {
            //$user_city = Db::name('user')->where(['id' => $user_id, 'status' => 1])->value('user_level');
            $data_list = Db::name('pickup_deliver')->where(['status' => 1])->select();

        }
        echo json_encode(array('ret' => 2, 'data' => $data_list, 'user_level' => $user_level, 'msg' => lang('查询成功')));
    }

     
     /**
     * 修改地址
     * @author 晓风  
     */
    public function address_edit($order_sn){
        
        if ($order_sn === null) $this->error('缺少参数');
        $info = OrderInfo::where("order_sn",$order_sn)->find();
        if(!$info){
            $this->error('数据异常');
        }
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();               
            Db::startTrans();
            try {
                $data["district_id"] = $data["district_id"][3] ?? 0;
                if(!$data["district_id"]){
                    $data['province'] = $info['province'];
                    $data['city'] = $info['city'];
                    $data['district'] = $info['district'];
                }               
                OrderInfo::editAddress($order_sn, $data);
                Db::commit();
            } catch (\Exception $e) {
                Db::rollback();
                $this->error($e->getMessage(), cookie('__forward__'));
            }
            $this->success('修改成功', cookie('__forward__'));
        }
      
        if($info['address_edit']){
            $this->error('地址已修改，无法再次修改');
        }
        $tips = "当前地址为：" . $info['province'] ."->".$info['city'] ."->" .$info['district'] . ";如不更改请勿选择";
        $info["district_id"] = 0;
        $fields = [         
            ['type' => 'text', 'name' => 'receiver_name', 'title' => '收件人', 'tips' => '', 'attr' => '', 'value' => ''],
            ['type' => 'text', 'name' => 'receiver_mobile', 'title' => '手机号', 'tips' => '', 'attr' => '', 'value' => ''],
            ['type' => 'linkages', 'name' => 'district_id', 'key' => 'id', 'option' => 'name', 'pid' => 'pid', 'title' => '修改省市区', 'level' => 3, 'table' => 'china_area',"tips"=>$tips],
            ['type' => 'text', 'name' => 'receiver_address', 'title' => '收货人地址', 'tips' => '', 'attr' => '', 'value' => ''],
        ];
        $this->assign('page_title', '编辑订单地址');
        $this->assign('page_tips', '只可更改一次地址，请于买家沟通后再修改，避免出现争议');
        $this->assign('form_items', $this->setData($fields, $info));
        return $this->fetch('admin@public/edit');
    }
    
      public function express_ex($id)
    {   
        $express = OrderGoodsExpress::get($id);     
        if(!$express || !$express["express_company_id"]){
            $this->error("未发货");
        }
        $express_company = \app\goods\model\ExpressCompany::get($express['express_company_id']);
        $express["express_company"] = $express_company;
        $express["ex"] =  \app\order\model\OrderGoodsExpress::getQuery($express["express_no"], $express_company["express_no"], $express["order_sn"]);  
        $this->assign('express', $express);
        return $this->fetch();
    }
}
